#pragma once
#include "Comm.hpp"
#include "Reactor.hpp"
#include "Service.hpp"
#include "Util.hpp"
#include "Sock.hpp"

// 链接管理器
int Accepter(Event *pev)
{
    std::cout << "有新的链接到来了,就绪的sock: " << pev->_sock << std::endl;
    while (true)
    {
        // Accept非阻塞等待,读取出错表示读取完毕,且状态码设置为EAGAIN or EWOULDBLOCK
        // accept和read一样,由于是非阻塞的ET模型,因此需要循环读取accept,保证新链接全部获取
        int new_sock = Sock::Accept(pev->_sock);
        if (new_sock < 0)
        {
            std::cout << "Accept done!" << std::endl;
            break;
        }
        std::cout << "Accept success!" << std::endl;
        SetNonBlock(new_sock);

        // 创建获取到的新链接对应的Event
        Event *other_pev = new Event;
        other_pev->_sock = new_sock;
        other_pev->_R = pev->_R;
        other_pev->RegisterCallback(Recver, Sender, Errorer);

        // 将Event插入到Reactor中
        pev->_R->InsertEvent(other_pev, EPOLLIN | EPOLLET);
    }
}